;
(function () {

  'use strict';

  angular.module('services.customActivity.summary', [])
    .constant('SUMMARY_MODULE', {

      BUS_VOLUME: {UPAY: 111, TMALL: 112, SCPAY: 113, BANK: 114, VCES: 115, LINGXI: 116},
      SUCCESS_VOLUME: {UPAY: 121, TMALL: 122, SCPAY: 123, BANK: 124, VCES: 125, LINGXI: 126},
      FAIL_VOLUME: {UPAY: 131, TMALL: 132, SCPAY: 133, BANK: 134, VCES: 135, LINGXI: 136},
      TOTAL_RATIO: {UPAY: 141, TMALL: 142, SCPAY: 143, BANK: 144, VCES: 145, LINGXI: 146},
      TOP_UP_PREFER: {UPAY: 151, TMALL: 152, SCPAY: 153, BANK: 154, VCES: 155, LINGXI: 156},
      BUS_VOLUME_CONTRASTIVE: {UPAY: 161, TMALL: 162, SCPAY: 163, BANK: 164, VCES: 165, LINGXI: 166},
      BUS_LINE_RATIO: 171,

      UPAY_SUCCESS_RATE: {BUS: 211, SYS: 212},
      PROVINCE_BUS_SUCCESS_RATE: {UPAY: 221, TMALL: 222, SCPAY: 223, BANK: 224, VCES: 225, LINGXI: 226},
      PROVINCE_SYS_SUCCESS_RATE: {UPAY: 231, TMALL: 232, SCPAY: 233, BANK: 234, VCES: 235, LINGXI: 236},
      TOTAL_BUS_SUCCESS_RATE: {UPAY: 241, TMALL: 242, SCPAY: 243, BANK: 244, VCES: 245, LINGXI: 246},
      TOTAL_SYS_SUCCESS_RATE: {UPAY: 251, TMALL: 252, SCPAY: 253, BANK: 254, VCES: 255, LINGXI: 256},
      PROVINCE_TOTAL_BUS_SUCCESS_RATE: 261,

      CHECKING_FILE: {UPAY: 311, TMALL: 312, SCPAY: 313, BANK: 314, VCES: 315, LINGXI: 316},
      CHECKING_DIFF: {UPAY: 321, TMALL: 322, SCPAY: 323, BANK: 324, VCES: 325, LINGXI: 326},

      PROVINCE_ASSESS: {TMALL: 412, SCPAY: 413, BANK: 414, VCES: 415, LINGXI: 416},

      HEALTH_MAX: 511,
      HEALTH_MIN: 512,
      HEALTH_AVG: 513,

      MAX_PROCESS_TIME: {UPAY: 611, TMALL: 612, SCPAY: 613, BANK: 614, VCES: 615, LINGXI: 616},
      AVG_PROCESS_TIME: {UPAY: 621, TMALL: 622, SCPAY: 623, BANK: 624, VCES: 625, LINGXI: 626},
      MIN_PROCESS_TIME: {UPAY: 631, TMALL: 632, SCPAY: 633, BANK: 634, VCES: 635, LINGXI: 636},
      MAX_TPS: {UPAY: 641, TMALL: 642, SCPAY: 643, BANK: 644, VCES: 645, LINGXI: 646},
      AVG_TPS: {UPAY: 651, TMALL: 652, SCPAY: 653, BANK: 654, VCES: 655, LINGXI: 656}
    })
    .service('summaryService', summaryService)
    .service('generatorSummaryPageService', generatorSummaryPageService)
    .service('pageConfigService', pageConfigService);

  function generatorSummaryPageService(Restangular, $compile) {

    var that = this;
    this.pageInfo = {};

    this.init = function (id, element, scope) {
      Restangular.all('sas/customActivity/summary/savedConfig/query').post({
        summaryId: id
      }).then(function (result) {
          if (result.state === '10000') {
            that.pageInfo = result.data;
            that.pageInfo.startTime = that.pageInfo.summaryStartTime.substring(0, 10);
            that.pageInfo.endTime = that.pageInfo.summaryEndTime.substring(0, 10);
            that.pageInfo.provinceCodes = that.pageInfo.summaryProvinceCode.split(',');
            //省code升序排列
            that.pageInfo.provinceCodes.sort(function (a, b) {
              a = parseInt(a);
              b = parseInt(b);
              if (a < b) {
                return -1;
              }
              if (a === b) {
                return 0;
              }
              else {
                return 1;
              }
            });
            element.empty().append($compile(that.pageInfo.layout)(scope));
            $(element).ckDrag();
          }
        }
      );
    };
  }

  generatorSummaryPageService.$inject = ['Restangular', '$compile'];

  function summaryService(Restangular, $state, $mdDialog) {

    var that = this;
    this.summaryList = [];//总结列表

    //选中总结
    this.selectedSummary = function (ev, obj) {
      Restangular.all('sas/customActivity/realTime/activityList/check').post({
        activityId: obj.activityId
      }).then(function (result) {
        if (result.state === '1005') {
          $state.go('sas.display', {summaryId: obj.summaryId});
        } else {
          alert('活动还未结束！');
        }
      });
    };

    //弹出活动设置页面
    //ev: 事件源
    //id: 总结ID
    //preview: 是否为预览页面跳转回来的
    this.showDialog = function (ev, id, preview) {
      ev.stopPropagation();
      $mdDialog.show({
        controller: ['$scope', 'pageConfigService', 'summaryId', 'previewed',
          function ($scope, pageConfigService, summaryId, previewed) {
            $scope.page = pageConfigService;
            if (summaryId) {
              $scope.page.editPage(summaryId, previewed);
              $scope.page.pageInfo.summaryId = summaryId;
            } else {
              $scope.page.newPage(previewed);
            }
          }
        ],
        templateUrl: 'views/customActivity/addSummaryActivity.html',
        parent: angular.element(document.body),
        targetEvent: ev,
        locals: {
          summaryId: id,
          previewed: preview
        }
      });
    };

    //总结列表查询
    this.querySummaryList = function () {
      that.loading = false;
      Restangular.one('sas/customActivity/summary/summaryList/query').get().then(
        function (result) {
          that.loading = true;
          if (result.state === '10000') {
            that.summaryList = result.data;
          } else {
            that.summaryList = [];
          }
        }
      );
    };

    //删除总结
    this.delSummary = function (ev, id) {
      ev.stopPropagation();
      if (confirm('删除后将无法恢复，您确定要删除吗？')) {
        Restangular.all('sas/customActivity/summary/summaryList/delete').post({
          summaryId: id
        }).then(function (result) {
            if (result.state === '10000') {
              that.querySummaryList();
            }
          }
        );
      }
    };
  };

  summaryService.$inject = ['Restangular', '$state', '$mdDialog'];

  function pageConfigService(Restangular, $state, $mdDialog, SUMMARY_MODULE, summaryService, generatorSummaryPageService) {

    var that = this;
    this.pageInfo = {};//页面信息
    this.activityList = [];//活动列表
    var previewed = false;//是否预览过
    var selectedModules = [];//保存上一次选择的模块

    this.editPage = function (id, preview) {
      previewed = preview;
      if (!previewed) {
        //查询保存的页面信息
        that.loading = false;
        Restangular.all('sas/customActivity/summary/savedConfig/query').post({
          summaryId: id
        }).then(function (result) {
            that.loading = true;
            if (result.state === '10000') {
              that.pageInfo = result.data;//保存页面信息
              //‘0’为true，非‘0’为false
              that.pageInfo.displaySetting.province = that.pageInfo.displaySetting.province === '0';
              that.pageInfo.displaySetting.time = that.pageInfo.displaySetting.time === '0';
              selectedModules = angular.copy(that.pageInfo.selectedModules);
              //查询活动列表
              Restangular.one('sas/customActivity/realTime/activityList/query').get().then(function (result) {
                  if (result.state === '10000') {
                    that.activityList = result.data;
                    //循环活动列表，选中活动主题
                    angular.forEach(that.activityList, function (obj) {
                      if (obj.activityId === that.pageInfo.activityId) {
                        that.switchActivity(obj);
                      }
                    });
                  }
                }
              );
              //查询模块列表
              Restangular.one('sas/customActivity/summary/configModules/query').get().then(function (result) {
                if (result.state === '10000') {
                  //选中已选择的模块
                  angular.forEach(result.data, function (root) {
                    angular.forEach(root.childModule, function (child) {
                      checking(child, that.pageInfo.selectedModules);
                    });
                  });
                  that.pageInfo.dataList = result.data;
                }
              });
            }
          }
        );
      }
    };

    //切换活动选项
    this.switchActivity = function (obj) {
      that.pageInfo.activityTime = obj.activityTime;
      that.pageInfo.activityProvince = obj.activityProvince;
      that.pageInfo.summaryTime = obj.activityTime;
      that.pageInfo.summaryProvince = obj.activityProvince;
      generatorSummaryPageService.pageInfo.startTime = obj.startTime.substring(0, 10);
      generatorSummaryPageService.pageInfo.endTime = obj.endTime.substring(0, 10);
      generatorSummaryPageService.pageInfo.provinceCodes = angular.copy(obj.provinceCode);
      generatorSummaryPageService.pageInfo.provinceCodes.sort(function (a, b) {
        a = parseInt(a);
        b = parseInt(b);
        if (a < b) {
          return -1;
        }
        if (a === b) {
          return 0;
        }
        else {
          return 1;
        }
      });
    };

    //新增页面窗口
    this.newPage = function (preview) {
      previewed = preview;
      if (!previewed) {
        that.pageInfo.activityId = 0;
        that.pageInfo.summaryId = 0;
        that.pageInfo.selectedModules = [];
        selectedModules = [];
        that.pageInfo.summaryName = '';
        that.pageInfo.displaySetting = {
          time: true,
          province: true
        };
        that.pageInfo.activityTime = '';
        that.pageInfo.activityProvince = '';
        that.pageInfo.layout = '';
        that.loading = false;
        Restangular.one('sas/customActivity/summary/configModules/query').get().then(function (result) {
          that.loading = true;
          if (result.state === '10000') {
            that.pageInfo.dataList = result.data;
          }
        });
        Restangular.one('sas/customActivity/realTime/activityList/query').get().then(function (result) {
            if (result.state === '10000') {
              that.activityList = result.data;
            }
          }
        );
      }
    };

    //判断选中的模块是否有变
    function isChanged() {
      var changed = false;
      if (selectedModules.length === that.pageInfo.selectedModules.length) {
        angular.forEach(selectedModules, function (v) {
          var has = false;
          angular.forEach(that.pageInfo.selectedModules, function (value) {
            if (v === value) {
              has = true;
            }
          });
          //如果当前模块没有找到，说明有变
          if (!has) {
            changed = true;
          }
        });
      } else {
        changed = true;
      }
      return changed;
    }

    //预览
    this.preview = function () {

      //必填校验
      if (!that.pageInfo.summaryName.trim()) {
        alert('页面名称不能为空！');
        return;
      }
      if (that.pageInfo.summaryName.trim().length > 30) {
        alert('页面名称的长度不能大于30个字符！');
        return;
      }
      if (!that.pageInfo.activityId) {
        alert('请选择一个活动主题！');
        return;
      }
      if (that.pageInfo.selectedModules.length === 0) {
        alert('请至少选择一个功能模块！');
        return;
      }

      generatorSummaryPageService.pageInfo.selectedModules = angular.copy(that.pageInfo.selectedModules);
      generatorSummaryPageService.pageInfo.preview = true;

      if (isChanged()) {
        that.pageInfo.layout = generatorTemplate();
      }

      $state.go('sas.summaryActivityEdit');
      $mdDialog.hide();
    };

    //取消或关闭
    this.cancel = function () {
      //确定关闭
      if (window.confirm('您确定要关闭窗口？关闭后数据将不保存')) {
        $mdDialog.hide();
        previewed = false;
        selectedModules = [];
      }
    };

    //新增页面
    function savePage(name) {
      Restangular.all('sas/customActivity/summary/summaryList/save').post({
        selectedModules: that.pageInfo.selectedModules,
        summaryName: name,
        activityId: that.pageInfo.activityId,
        displaySetting: {
          time: that.pageInfo.displaySetting.time ? 0 : 1,
          province: that.pageInfo.displaySetting.province ? 0 : 1
        },
        layout: previewed ? that.pageInfo.layout : generatorTemplate()
      }).then(function (result) {
        if (result.state === '10000') {
          alert('新增重大活动总结页面成功！');
          summaryService.querySummaryList();
          $mdDialog.hide();
          previewed = false;
          selectedModules = [];
        } else {
          alert(result.message);
        }
      });
    }

    //更新页面
    function updatePage(name) {
      if (isChanged()) {
        that.pageInfo.layout = generatorTemplate();
      }
      Restangular.all('sas/customActivity/summary/summaryList/update').post({
        summaryId: that.pageInfo.summaryId,
        selectedModules: that.pageInfo.selectedModules,
        summaryName: name,
        activityId: that.pageInfo.activityId,
        displaySetting: {
          time: that.pageInfo.displaySetting.time ? 0 : 1,
          province: that.pageInfo.displaySetting.province ? 0 : 1
        },
        layout: that.pageInfo.layout
      }).then(function (result) {
        if (result.state === '10000') {
          alert('修改重大活动总结页面成功！');
          summaryService.querySummaryList();
          $mdDialog.hide();
          previewed = false;
          selectedModules = [];
        } else {
          alert(result.message);
        }
      });
    }

    //根据选择的模块自动生成模板
    function generatorTemplate() {
      var template = '';
      angular.forEach(SUMMARY_MODULE, function (value, key) {
        var has = false;
        if (typeof value === 'object') {
          angular.forEach(value, function (v, k) {
            if (that.pageInfo.selectedModules.indexOf(v) > -1) {
              has = true;
            }
          });
        } else {
          if (that.pageInfo.selectedModules.indexOf(value) > -1) {
            has = true;
          }
        }
        if (has) {
          template += ('<summary-' + key.replace(/_/g, '-').toLowerCase() + '-layout></summary-' + key.replace(/_/g, '-').toLowerCase() + '-layout>' );
        }
      });
      selectedModules = angular.copy(that.pageInfo.selectedModules);
      return template;
    }

    //提交
    this.confirm = function (ev) {

      //必填校验
      if (!that.pageInfo.summaryName.trim()) {
        alert('页面名称不能为空！');
        return;
      }
      if (that.pageInfo.summaryName.trim().length > 30) {
        alert('页面名称的长度不能大于30个字符！');
        return;
      }
      if (!that.pageInfo.activityId) {
        alert('请选择一个活动主题！');
        return;
      }
      if (that.pageInfo.selectedModules.length === 0) {
        alert('请至少选择一个功能模块！');
        return;
      }

      //如果有总结ID则为修改
      if (that.pageInfo.summaryId) {
        //关闭新增页面
        $mdDialog.hide();
        //弹出确定页面
        $mdDialog.show({
          controller: ['$scope',
            function ($scope) {
              $scope.choose = true;//是否新增还是覆盖
              $scope.pageName = '';//页面名称
              //确定
              $scope.ok = function () {
                if ($scope.choose) {
                  if (!$scope.pageName.trim()) {
                    alert('页面名称不能为空！');
                    return;
                  }
                  if ($scope.pageName.trim().length > 30) {
                    alert('页面名称的长度不能大于30个字符！');
                    return;
                  }
                  savePage($scope.pageName);
                } else {
                  //覆盖
                  updatePage(that.pageInfo.summaryName);
                }
              };
              //关闭
              $scope.cancel = function () {
                if (window.confirm("您确定要关闭窗口？关闭后数据将不保存")) {
                  $mdDialog.hide();
                  summaryService.showDialog(ev, that.pageInfo.summaryId, previewed);
                }
              };
            }
          ],
          templateUrl: 'views/customActivity/summaryConfirm.html',
          parent: angular.element(document.body)
        });
      } else {
        //新增页面信息
        savePage(that.pageInfo.summaryName);
      }
    }

    //新增模块
    function addModule(id) {
      var has = false;
      //如果找到相同的ID，就添加到数组中
      angular.forEach(that.pageInfo.selectedModules, function (moduleId) {
        if (id === moduleId) {
          has = true;
        }
      });
      has || that.pageInfo.selectedModules.push(id);
    }

    //删除模块
    function delModule(id) {
      //找到相同就删除
      angular.forEach(that.pageInfo.selectedModules, function (moduleId, index) {
        if (id === moduleId) {
          that.pageInfo.selectedModules.splice(index, 1);
        }
      });
    }

    //选中父节点
    this.checkedChild = function (child) {
      //子模块与父模块同为选中或未选中状态
      angular.forEach(child.childModule, function (subChild) {
        subChild.checked = child.checked;
        if (child.checked) {
          addModule(subChild.moduleId);
        } else {
          delModule(subChild.moduleId);
        }
      });
    };

    //选中子节点
    this.checkedSubChild = function (child, sub) {
      child.checked = sub.checked;//将子节点的值赋给父节点，如果为false，则父节点也为false
      if (child.checked) {
        //如果为true 判断父节点里所有子节点是否都为选中状态
        angular.forEach(child.childModule, function (subChild) {
          if (!subChild.checked) {
            child.checked = false;//有一个没选中，则父节点也不能被选中
          }
        });
        //将选中的节点添加到模块中
        addModule(sub.moduleId);
      } else {
        //移除选中的节点
        delModule(sub.moduleId);
      }
    };

    //根据模块列表，将对应模块选中
    function checking(child, selectedModules) {
      var count = 0;
      angular.forEach(child.childModule, function (subChild) {
        //将子模块初始化为false，当找到相同的模块ID后，选中状态改为true
        subChild.checked = false;
        angular.forEach(selectedModules, function (moduleId) {
          if (subChild.moduleId === moduleId) {
            subChild.checked = true;
            count++;//记录被选中的模块数
          }
        });
      });
      //如果子模块全部被选中，那么父模块则为选中状态
      child.checked = count && count === child.childModule.length;
    }
  }

  pageConfigService.$inject = ['Restangular', '$state', '$mdDialog', 'SUMMARY_MODULE', 'summaryService', 'generatorSummaryPageService'];
})();